package com.zdw.oauth.config.international;

import cn.hutool.core.util.StrUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 本地语言配置类
 */
@Configuration
public class LanguageConfig implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //默认设置本地为中文,中国
        Locale locale = Locale.CHINA;
        //获取请求头中的国际化/多语言标识:Accept-Language
        String language = request.getHeader("Accept-Language");
        System.out.println("国际化/多语言Accept-Language:" + language);
        if (StrUtil.isNotBlank(language)) {
            String[] splitLanguage = language.split("_");
            if (splitLanguage.length > 1) {
                //根据请求头参数,初始化本地语言和地区
                locale = new Locale(splitLanguage[0], splitLanguage[1]);
            }
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }

    @Bean
    public LocaleResolver localeResolver() {
        return new LanguageConfig();
    }

}
